package thread;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * 这是一个简单的join/forck计算过程，将1-1001数字相加
 */
public class ForkJoinTest {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ForkJoinPool pool= new ForkJoinPool();
        ForkJoinTask<Integer> taskFuture= pool.submit(new MyForkJoinTask(1,8));
        Integer integer = taskFuture.get();
        System.out.println(integer);
    }



}

class MyForkJoinTask extends RecursiveTask<Integer>{

    private static  final Integer MAX=200;

    private Integer startValue;

    private Integer endValue;

    public MyForkJoinTask(Integer startValue, Integer endValue) {
        this.startValue = startValue;
        this.endValue = endValue;
    }

    @Override
    protected Integer compute() {

        if(endValue-startValue<MAX){
            System.out.println("开始计算的部分 startValue="+startValue+",endValue="+endValue);
            Integer totalValue=0;
            for(int index=this.startValue; index<=this.endValue;index++){
                totalValue+=index;
            }
            return totalValue;
        }else{
            MyForkJoinTask subTask1= new MyForkJoinTask(startValue,(startValue+endValue)/2);
            MyForkJoinTask subTask2= new MyForkJoinTask((startValue+endValue)/2+1,endValue);
            subTask1.fork();
            subTask2.fork();
            return subTask1.join()+subTask2.join();

        }


    }
}
